package com.fen.testdemo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Test {

   final static ExecutorService executor = Executors.newFixedThreadPool(2);

   public static void main(String[] args) { 
       RpcService rpcService = new RpcService(); 
       HttpService httpService = new HttpService();

       Future<Map<String, String>> future1 = null;

       Future<Integer> future2 = null;
       try { 
           future1 = executor.submit(rpcService::getRpcResult);
           future2 = executor.submit(httpService::getHttpResult);
           //耗时10ms 
           Map<String, String> result1 = future1.get(10000, TimeUnit.MILLISECONDS);
           //耗时20ms 
           Integer result2 = future2.get(20000, TimeUnit.MILLISECONDS);
           //总耗时20ms 
       } catch (Exception e) { 
           if (future1 != null) { 
                future1.cancel(true); 
           } 
           if (future2 != null) { 
                future2.cancel(true); 
           } 
           throw new RuntimeException(e); 
       } 
    } 
   static class RpcService { 
       Map<String, String> getRpcResult() throws Exception { 
           //调用远程方法（远程方法耗时约10ms，可以使用Thread.sleep模拟）
           Thread.sleep(10000);
           return new HashMap<>();
       } 
    } 
   static class HttpService { 
       Integer getHttpResult() throws Exception { 
           //调用远程方法（远程方法耗时约20ms，可以使用Thread.sleep模拟）
           Thread.sleep(20000);
           return 0;
       } 
    } 
} 